//
//  ViewController.swift
//  SnapTest
//
//  Created by jerry on 2019/2/22.
//  Copyright © 2019 刘杰. All rights reserved.
//

import UIKit
import Photos;
class ViewController: UIViewController,PHPhotoLibraryChangeObserver {

    @IBOutlet weak var _imgv: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        PHPhotoLibrary.shared().register(self)
        PHPhotoLibrary.requestAuthorization { (s) in
            
        }
        NotificationCenter.default.addObserver(self, selector: #selector(ff), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
//            print("get last")
//            self.getlast()
        }
    }
    @objc func ff(notification: Notification){
        print("fewfweafweafawe")
    }
    func getlast(){
        let options: PHFetchOptions = PHFetchOptions();
        
        options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)];
        let rs: PHFetchResult = PHAsset.fetchAssets(with: options)
        let asset = rs.object(at: 0)
        if asset.mediaSubtypes.contains(PHAssetMediaSubtype.photoScreenshot){
            print("检测到截屏")
            let resRequestOpt = PHImageRequestOptions.init()
            resRequestOpt.isNetworkAccessAllowed = false
            PHImageManager.default().requestImageData(for: rs.object(at: 0), options: resRequestOpt) { (data, dataUTI, imageOrientation, info) in
                let img = UIImage.init(data: data!)!
                self._imgv.image = img
            }
        }
    }
    @IBAction func onlickxxx(_ sender: Any) {
        getlast()
    }
    
    public func photoLibraryDidChange(_ changeInstance: PHChange){
        print("监听到相册变更")
    }
}

